package xing.service.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import xing.application.api.WechatApi;
import xing.domain.wechat.LoginInfo;
import xing.infrastructure.data.CallResult;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/********************************
 * 文 件 名 :WechatController.java
 * 创 建 人：陈天龙
 * 日    期：2017/10/16
 * 描   述：微信小程序对接控制层
 * 版 本 号：v1.0.0
 ********************************/
@Api(value = "微信小程序登录态维护",description = "微信小程序登录态维护相关的Api")
@RestController
@RequestMapping("/wechatservice")
public class WechatController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatApi wechatApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 描   述：获取第三方sessionId
     * 创 建 人：陈天龙
     * 日    期：2017/10/16
     * @return CallResult
     */
    @ApiOperation(value="第三方sessionid获取", notes="第三方sessionid获取",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "jscode", value = "登录信息获取的code", required = true, dataType = "String",paramType = "path")
    @GetMapping("/thirdSession/{jscode}")
    public CallResult getsession(HttpServletRequest request, @PathVariable("jscode") String jscode){
        logger.info("获取的jscode为"+jscode);
        //生成第三方sessionId,绑定session_key和openId并存入缓存中
        String res = wechatApi.jscode2Session(jscode);
        CallResult cr = CallResult.ok();
        try {
            JSONObject jsonObject = JSON.parseObject(res);
            Integer errcode = jsonObject.getInteger("errcode");
            if(null == errcode){
                String openid = jsonObject.getString("openid");
                String sessionKey = jsonObject.getString("session_key");
                //存入缓存中
                String thirdSessionId = request.getSession(true).getId();
                redisTemplate.opsForValue().set(thirdSessionId,sessionKey+"|"+openid);
                redisTemplate.expire(thirdSessionId,1800, TimeUnit.SECONDS);
                cr.setData(thirdSessionId);
            }else{
                cr = CallResult.error(jsonObject.getString("errmsg"));
                logger.error("获取第三方session失败",res);
            }
        } catch (Exception e) {
            logger.error("获取第三方session失败",e);
            cr = CallResult.error("系统异常");
        }
        return cr;
    }

    /**
     * 描   述：解密用户敏感数据
     * 创 建 人：陈天龙
     * 日    期：2017/10/16
     * @return CallResult
     */
    @ApiOperation(value="用户信息解密", notes="用户信息解密",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "loginInfo", value = "登录信息参数encryptedData,iv,sessionId", required = true, dataType = "LoginInfo")
    @PostMapping("/decodeUserInfo")
    public CallResult decodeUserInfo(@RequestBody LoginInfo loginInfo){
        return wechatApi.decodeUserInfo(loginInfo.getEncryptedData(),loginInfo.getIv(),loginInfo.getSessionId(),loginInfo.getDesType());
    }
}
